package com.serialcommunication.helper;

import java.math.BigInteger;

import org.apache.soap.encoding.Hex;

public class HexUtil {

	public static Hex intToHex(int pValue) {
		String valueAsString = String.valueOf(pValue);
		valueAsString = valueAsString.replaceAll(" ", "");
		while ((valueAsString.length() % 2) != 0) {
			valueAsString = "0" + valueAsString;
		}
		return new Hex(valueAsString);
	}

	public static int hexToInt(Hex hex) {
		return Integer.decode(hex.toString());
	}

	public static int hexToInt(String hex) {
		return Integer.decode(hex);
	}

	/**
	 * 
	 * @param s
	 *            the string as base for the hex
	 * @param numberOfBytes
	 *            define byte length the length of the returned hex
	 * @return
	 */
	public static Hex generateHexForBytes(String s, int numberOfBytes) {
		String temp = s.replaceAll(" ", "");
		while (temp.length() % (numberOfBytes * 2) != 0) {
			temp = "0" + temp;
		}
		return new Hex(temp);
	}

	/**
	 * Generates a hex using a string.
	 * @param s
	 *            the string as base for the hex. the absolute length has to be
	 *            2
	 * @return
	 */
	public static Hex generateHexForOneByte(String s) {
		s = s.replaceAll(" ", "");
		if (s.length() != 2) {
			s = "0" + s;
		}
		return new Hex(s);
	}
}
